<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      th:replace="~{admin/layout/base :: html(~{::title}, ~{::content}, ~{::script})}">
<head>
    <title>系统概览 - 废物回收管理系统</title>
</head>
<body>
<th:block th:fragment="content">
    <!-- 引入 Chart.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    
    <!-- 统计卡片 -->
    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <div class="stat-card">
                <div class="icon bg-primary bg-opacity-10 text-primary">
                    <i class='bx bxs-calendar'></i>
                </div>
                <div class="title">今日订单</div>
                <div class="value" th:text="${todayOrders}">0</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="icon bg-success bg-opacity-10 text-success">
                    <i class='bx bxs-user'></i>
                </div>
                <div class="title">活跃用户</div>
                <div class="value" th:text="${activeUsers}">0</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="icon bg-warning bg-opacity-10 text-warning">
                    <i class='bx bxs-package'></i>
                </div>
                <div class="title">回收总量(kg)</div>
                <div class="value" th:text="${#numbers.formatDecimal(totalWeight, 1, 1)}">0.0</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card">
                <div class="icon bg-info bg-opacity-10 text-info">
                    <i class='bx bx-money'></i>
                </div>
                <div class="title">系统收入(元)</div>
                <div class="value" th:text="${#numbers.formatDecimal(totalIncome, 1, 2)}">0.00</div>
            </div>
        </div>
    </div>

    <!-- 图表区域 -->
    <div class="row g-3 mb-4">
        <div class="col-md-8">
            <div class="content-card">
                <h5 class="mb-3">订单趋势</h5>
                <div style="position: relative; height: 300px;">
                    <canvas id="orderTrendChart"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="content-card">
                <h5 class="mb-3">物品分布</h5>
                <div style="position: relative; height: 300px;">
                    <canvas id="itemDistributionChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 最近订单 -->
    <div class="content-card">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h5 class="mb-0">最近订单</h5>
            <a href="/admin/orders" class="btn btn-sm btn-primary">查看全部</a>
        </div>
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>订单号</th>
                        <th>用户</th>
                        <th>回收员</th>
                        <th>物品类型</th>
                        <th>重量(kg)</th>
                        <th>金额(元)</th>
                        <th>状态</th>
                        <th>创建时间</th>
                    </tr>
                </thead>
                <tbody>
                    <tr th:each="order : ${recentOrders}">
                        <td th:text="${order.orderNo}">ON202502100001</td>
                        <td th:text="${order.userName}">张三</td>
                        <td th:text="${order.collectorName ?: '-'}">李四</td>
                        <td th:text="${order.itemType}">纸类</td>
                        <td th:text="${order.actualWeight ?: order.estimatedWeight}">5.0</td>
                        <td th:text="${#numbers.formatDecimal(order.price ?: 0, 1, 2)}">25.00</td>
                        <td>
                            <span th:class="${'badge ' + 
                                (order.status == 'PENDING' ? 'bg-warning' :
                                 order.status == 'PROCESSING' ? 'bg-info' :
                                 order.status == 'COMPLETED' ? 'bg-success' : 'bg-danger')}"
                                  th:text="${order.status == 'PENDING' ? '待处理' :
                                           order.status == 'PROCESSING' ? '处理中' :
                                           order.status == 'COMPLETED' ? '已完成' : '已取消'}">
                                已完成
                            </span>
                        </td>
                        <td th:text="${#temporals.format(order.createTime, 'yyyy-MM-dd HH:mm')}">2025-02-10 10:00</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <script th:inline="javascript">
    // 使用window对象来存储全局状态
    window.chartsInitialized = window.chartsInitialized || false;
    
    function initCharts() {
        if (window.chartsInitialized) {
            return;
        }
        
        try {
            // 订单趋势图
            const trendChartEl = document.getElementById('orderTrendChart');
            if (trendChartEl && typeof Chart !== 'undefined') {
                const trendData = /*[[${orderTrend}]]*/ [];
                console.log('订单趋势数据:', trendData);
                
                // 确保数据按月份排序
                trendData.sort((a, b) => a.month.localeCompare(b.month));
                
                const labels = trendData.map(item => item.month);
                const values = trendData.map(item => item.count);
                
                new Chart(trendChartEl, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: '订单数量',
                            data: values,
                            borderColor: 'rgb(75, 192, 192)',
                            backgroundColor: 'rgba(75, 192, 192, 0.2)',
                            fill: true,
                            tension: 0.4,
                            pointRadius: 4,
                            pointHoverRadius: 6
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: true,
                                position: 'top'
                            },
                            tooltip: {
                                mode: 'index',
                                intersect: false
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true,
                                ticks: {
                                    stepSize: 1
                                }
                            }
                        },
                        interaction: {
                            mode: 'nearest',
                            axis: 'x',
                            intersect: false
                        }
                    }
                });
            }
            
            // 物品分布图
            const distributionChartEl = document.getElementById('itemDistributionChart');
            if (distributionChartEl && typeof Chart !== 'undefined') {
                const distributionData = /*[[${itemDistribution}]]*/ [];
                console.log('物品分布数据:', distributionData);
                
                // 类型名称映射
                const typeMap = {
                    'PLASTIC': '塑料',
                    'METAL': '金属',
                    'PAPER': '纸张',
                    'GLASS': '玻璃',
                    'FABRIC': '布料',
                    'ELECTRONICS': '电子',
                    'OTHER': '其他'
                };
                
                // 过滤掉 null 类型和合并相同类型，并转换为中文
                const processedData = distributionData.reduce((acc, curr) => {
                    if (curr.type === null) return acc;
                    const type = curr.type.toUpperCase();
                    const typeName = typeMap[type] || type;
                    const existingItem = acc.find(item => item.type === typeName);
                    if (existingItem) {
                        existingItem.count += curr.count;
                    } else {
                        acc.push({type: typeName, count: curr.count});
                    }
                    return acc;
                }, []);
                
                const labels = processedData.map(item => item.type);
                const values = processedData.map(item => item.count);
                
                new Chart(distributionChartEl, {
                    type: 'doughnut',
                    data: {
                        labels: labels,
                        datasets: [{
                            data: values,
                            backgroundColor: [
                                'rgba(255, 99, 132, 0.8)',
                                'rgba(54, 162, 235, 0.8)',
                                'rgba(255, 205, 86, 0.8)',
                                'rgba(75, 192, 192, 0.8)',
                                'rgba(153, 102, 255, 0.8)'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: true,
                                position: 'right'
                            }
                        },
                        layout: {
                            padding: 20
                        }
                    }
                });
            }
            
            // 标记图表已初始化
            window.chartsInitialized = true;
            
        } catch (error) {
            console.error('初始化图表时出错:', error);
        }
    }
    
    // 页面加载完成后初始化图表
    document.addEventListener('DOMContentLoaded', initCharts);
    </script>
</th:block>
</body>
</html> 